﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DcsGauges.Server.Network;
using System.Windows.Media.Imaging;

namespace DcsGauges.Server.Models
{
    class ServerModel
    {
        #region Fields / Properties

        private DataDispatcher          dataDispatcher                  = null;

        public BitmapSource ConnectedGameClientLogo 
        { 
            get { return this.dataDispatcher.DataSource != null ? this.dataDispatcher.DataSource.Logo : null; }
        }

        public string ConnectedGameClient
        {
            get { return this.dataDispatcher.DataSource != null ? this.dataDispatcher.DataSource.GameName : "None"; }
        }

        public ICollection<IDcsGaugesClientChannel> DcsGaugesClients
        {
            get { return this.dataDispatcher.DataSinks; }
        }

        public bool IsServerRunning
        {
            get { return ServerEndpoint.Instance.IsRunning; }
        }

        #endregion


        #region Events
        
        public event EventHandler       ServerModelChangedEvent;

        #endregion


        #region Constructors

        public ServerModel()
        {
            this.dataDispatcher                                     = new DataDispatcher();
            ServerEndpoint.Instance.GameClientConnectedEvent        += OnGameClientConnectedEvent;
            ServerEndpoint.Instance.DcsGaugesClientConnectedEvent   += OnInstanceDcsGaugesClientConnectedEvent;
        }

        #endregion


        #region Event Handlers

        void OnInstanceDcsGaugesClientConnectedEvent(object sender, ServerEndpoint.DcsGaugesClientConnectedEventArgs e)
        {
            this.dataDispatcher.RegisterDataSink(e.Channel);
            this.FireServerModelChanged();
        }

        void OnGameClientConnectedEvent(object sender, ServerEndpoint.GameClientConnectedEventArgs e)
        {
            this.dataDispatcher.SetDataSource(e.Channel);
            this.FireServerModelChanged();
        }

        void OnDataDispachterChanged(object sender, EventArgs e)
        {
            this.FireServerModelChanged();
        }

        #endregion


        #region Operations

        public void Start()
        {
            ServerEndpoint.Instance.Start();
            this.FireServerModelChanged();
        }

        public void Stop()
        {
            ServerEndpoint.Instance.Stop();
            this.FireServerModelChanged();
        }

        #endregion


        #region Helpers & Internals
        
        private void FireServerModelChanged()
        {
            if(this.ServerModelChangedEvent != null)
                this.ServerModelChangedEvent(this, new EventArgs());
        }

        #endregion
    }
}
